package com.xuzhiguang.light.gateway.core.context;

import com.xuzhiguang.light.gateway.common.request.GatewayRequest;
import com.xuzhiguang.light.gateway.common.request.RequestContext;
import com.xuzhiguang.light.gateway.common.response.GatewayResponse;
import com.xuzhiguang.light.gateway.core.route.GatewayRoute;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xuzhiguang
 */

public class GatewayContext {

    @Getter
    private GatewayRequest request;

    @Getter
    @Setter
    private GatewayResponse response;

    @Getter
    private RequestContext requestContext;

    @Getter
    private GatewayRoute route;

    @Getter
    private final Map<String, Object> attributes = new ConcurrentHashMap<>();

    @Getter
    @Setter
    private Throwable throwable;

    private GatewayContext() {

    }

    public Object getAttribute(String name) {
        return attributes.get(name);
    }

    public Object getAttributeOrDefault(String name, Object defaultVal) {
        return attributes.getOrDefault(name, defaultVal);
    }

    public void putAttribute(String name, Object obj) {
        attributes.put(name, obj);
    }

    public boolean isError() {
        return throwable != null;
    }

    public static class Builder {
        private GatewayContext context;

        public Builder() {
            this.context = new GatewayContext();
        }

        public Builder request(GatewayRequest request) {
            context.request = request;
            return this;
        }

        public Builder requestContext(RequestContext requestContext) {
            context.requestContext = requestContext;
            return this;
        }

        public Builder route(GatewayRoute route) {
            context.route = route;
            return this;
        }

        public GatewayContext build() {
            return this.context;
        }

    }

}
